<template>
  <div>
    <!--    序列号相关详情 Start-->
    <!--    序列号分类-->
    <el-form
      v-if="rule && rule.level === 1"
      label-width="80px"
      label-position="left"
      class="no-bottom-form column-two-form"
      :inline="true"
      style="width: 100%; margin: 0 auto"
    >
      <el-form-item label="类型">
        <span class="limitLength" title="序列号分类">序列号分类</span>
      </el-form-item>
      <el-form-item label="名称">
        <span class="limitLength" :title="rule.ruleName">{{
          rule.ruleName
        }}</span>
      </el-form-item>
      <el-form-item label="修改人">
        <span class="limitLength" :title="rule.modifyBy">{{
          rule.modifyBy
        }}</span>
      </el-form-item>
      <el-form-item label="修改时间">
        <span
          class="limitLength"
          :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')"
        >
          {{ moment(rule.modifyDate).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </el-form-item>
    </el-form>
    <!--    序列号规则 -->
    <el-form
      v-if="rule.level === 2"
      label-width="80px"
      label-position="left"
      class="no-bottom-form column-three-form"
      :inline="true"
      style="width: 100%; margin: 0 auto"
    >
      <el-form-item label="分类">
        <span class="limitLength" title="序列号规则"
          >序列号规则{{
            rule.ruleType === "DYNAMIC" ? "（动态）" : "（静态）"
          }}</span
        >
      </el-form-item>
      <el-form-item label="名称">
        <span class="limitLength" :title="rule.ruleName">{{
          rule.ruleName
        }}</span>
      </el-form-item>
      <el-form-item label="编码">
        <span class="limitLength" :title="rule.ruleCode">{{
          rule.ruleCode
        }}</span>
      </el-form-item>
      <el-form-item label="修改人">
        <span class="limitLength" :title="rule.modifyBy">{{
          rule.modifyBy
        }}</span>
      </el-form-item>
      <el-form-item style="width: 55%" label="修改时间">
        <span
          class="limitLength"
          :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')"
        >
          {{ moment(rule.modifyDate).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </el-form-item>
    </el-form>
    <!--    序列号实例-->
    <el-form
      v-if="rule.level === 3"
      label-width="80px"
      label-position="left"
      class="no-bottom-form column-two-form"
      :inline="true"
      style="width: 100%; margin: 0 auto"
    >
      <el-form-item label="类型">
        <span class="limitLength" title="序列号实例">序列号实例</span>
      </el-form-item>
      <el-form-item label="名称">
        <span class="limitLength" :title="rule.ruleName">{{
          rule.ruleName
        }}</span>
      </el-form-item>
      <el-form-item label="编码">
        <span class="limitLength" :title="rule.ruleCode">{{
          rule.ruleCode
        }}</span>
        <el-button
          style="vertical-align: inherit; margin-left: 10px"
          type="text"
          @click="copy(rule.ruleCode)"
          icon="el-icon-document-copy"
        ></el-button>
      </el-form-item>
      <el-form-item label="流水号当前值" label-width="140px">
        <span class="limitLength" :title="rule.currentSerialNum">{{
          rule.currentSerialNum
        }}</span>
      </el-form-item>
      <el-form-item label="修改人">
        <span class="limitLength" :title="rule.modifyBy">{{
          rule.modifyBy
        }}</span>
      </el-form-item>
      <el-form-item label="修改时间">
        <span
          class="limitLength"
          :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')"
        >
          {{ moment(rule.modifyDate).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </el-form-item>
    </el-form>

    <!--      序列号区段 start-->
    <h4 v-if="rule.level === 2">规则配置</h4>
    <el-form
      v-loading="ruleLoading"
      v-if="rule.level === 2"
      label-width="80px"
      label-position="left"
      class="mt20"
      ref="form"
      :model="form"
      style="width: 100%; margin: 0 auto"
    >
      <el-form-item style="margin-bottom: 0px" label="长度限制">
        <span>{{ allLength }}</span>
      </el-form-item>

      <el-form-item label="区段定义" required>
        <div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAddSection"
            >添加区段</el-button
          >
          <el-row
            v-for="(r, index) in sectionList"
            style="margin-top: 8px"
            :key="r.name"
          >
            <el-button
              @click="handleEditSection(r, index)"
              class="limitLength"
              >{{ r.name }}</el-button
            >
            <span>{{ "（" + r.sectionType + "）" }}</span>
            <i
              class="el-icon-delete"
              @click="handleDelSection(index)"
              style="margin-left: 10px"
            />
            <i
              class="el-icon-top"
              v-if="index"
              @click="handleUpSection(index)"
              style="margin-left: 10px"
            />
            <i
              class="el-icon-bottom"
              v-if="index !== sectionList.length - 1"
              @click="handleDownSection(index)"
              style="margin-left: 10px"
            />
          </el-row>
        </div>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          type="textarea"
          v-model="form.description"
          :maxlength="255"
          show-word-limit
        ></el-input>
      </el-form-item>
      <div style="text-align: center">
        <el-button :loading="saveLoading" @click="handleSave" type="primary"
          >保存</el-button
        >
        <el-button style="margin-left: 8px" @click="handleReset"
          >重置</el-button
        >
        <el-button
          :disabled="!sectionList.length"
          style="margin-left: 8px"
          type="primary"
          @click="handlePreview"
          >预览</el-button
        >
      </div>
    </el-form>

    <!--      序列号区段 start-->
    <!--    序列号规则详情 End-->
    <section-modal ref="sectionModal" @ok="hanleSureSection"></section-modal>
    <rule-preview-modal ref="rulePreviewModal"></rule-preview-modal>
  </div>
</template>

<script>
import { copy } from "@/utils/util";
import moment from "moment";
import SectionModal from "./sectionModal.vue";
import RulePreviewModal from "./rulePreviewModal.vue";

import { putTechserialnum } from "@/apis/paas/TechSerialNumController.js";
import { putTechdefinesection } from "@/apis/paas/TechDefineSectionController.js";
export default {
  name: "RuleConfigForm",
  components: {
    SectionModal,
    RulePreviewModal,
  },
  props: {
    rule: {
      type: Object,
      default: () => {},
    },
    sectionList: {
      type: Array,
      default: () => [],
    },
  },
  filters: {
    attributeTypeFilter(value) {
      const map = {
        FIXED: "Fixed",
        PARAM: "Param",
        AUT0: "Auto",
        DATETIME: "DateTime",
      };
      return map[value] || "";
    },
  },
  watch: {
    sectionList: {
      handler() {
        if (this.sectionList && this.sectionList.length) {
          this.allLength = 0;
          this.sectionList.forEach((item) => {
            if (
              item.sectionType === "Param" ||
              item.sectionType === "Placeholder" ||
              item.sectionType === "Auto"
            ) {
              this.allLength += item.startLength;
            } else if (item.sectionType === "Fixed") {
              this.allLength += item.parameter.length;
            } else if (item.sectionType === "DateTime") {
              this.allLength += item.dateType.length;
            }
          });
        } else {
          this.allLength = "";
        }
      },
      deep: true,
    },
    "rule.description": {
      handler(newValue) {
        this.$nextTick(() => {
          this.form.description = newValue;
        });
      },
      deep: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.form.description = this.rule.description;
    });
  },
  data() {
    return {
      copy,
      moment,
      recordSectionList: [],
      allLength: "",
      ruleLoading: false,
      saveLoading: false,
      form: {
        description: "",
      },
    };
  },
  methods: {
    handleUpSection(index) {
      const beforeObj = this.sectionList[index - 1];
      this.$set(this.sectionList, index - 1, this.sectionList[index]);
      this.$set(this.sectionList, index, beforeObj);
    },
    handleDownSection(index) {
      const afterObj = this.sectionList[index + 1];
      this.$set(this.sectionList, index + 1, this.sectionList[index]);
      this.$set(this.sectionList, index, afterObj);
    },
    // 前端删除区段
    handleDelSection(index) {
      this.sectionList.splice(index, 1);
    },
    handleEditSection(section, index) {
      this.$refs.sectionModal.edit(
        section,
        index,
        this.sectionList,
        this.rule.startLength,
        this.rule.ruleType
      );
    },
    handleAddSection() {
      // 添加区段
      this.$refs.sectionModal.add(
        this.sectionList,
        this.rule.id,
        this.rule.startLength,
        this.rule.ruleType
      );
    },
    // sectionmodal 确定事件  更新区段
    hanleSureSection(callback) {
      // edit
      if (callback.index !== null) {
        this.$set(this.sectionList, callback.index, callback.section);
      } else {
        // add 新增
        this.sectionList.push(callback.section);
      }
    },
    // 保存规则 区段
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.sectionList.length <= 0) {
            this.$message.error("区段不能为空");
            return;
          }
          const autoFlag = this.sectionList.some(
            (item) => item.sectionType === "Auto"
          );
          if (!autoFlag) {
            this.$message.error("Auto类型区段不能为空");
            return;
          }
          // 保存描述
          const req = {
            id: this.rule.id,
            ruleName: this.rule.ruleName,
            ruleCode: this.rule.ruleCode,
            description: this.form.description,
          };
          this.saveLoading = true;
          putTechserialnum(req)
            .then(() => {})
            .finally(() => {
              this.saveLoading = false;
            });

          // 保存区段
          this.saveLoading = true;
          this.ruleLoading = true;
          putTechdefinesection({
            sectionList: this.sectionList,
          })
            .then(() => {
              this.$message.success("操作成功");
              this.$emit("reset", this.rule.id);
            })
            .finally(() => {
              this.saveLoading = false;
              this.ruleLoading = false;
            });
        }
      });
    },
    handleReset() {
      this.$emit("reset", this.rule.id);
      this.$nextTick(() => {
        this.form = {
          startLength: "",
          description: "",
        };
      });
    },
    // 预览
    handlePreview() {
      // 校验数组是否已保存recordSectionList recordList
      if (
        JSON.stringify(this.sectionList) !==
        JSON.stringify(this.recordSectionList)
      ) {
        this.$notify({
          title: "警告",
          message: "规则配置已变更，请保存结果后预览",
          type: "warning",
        });
        return false;
      }
      this.$refs.rulePreviewModal.open(this.rule, this.sectionList);
    },
    formatter(value) {
      return parseInt(value.toString().slice(0, 6)) || "";
    },
    selfValidator(rule, value, callback) {
      // if (value.toString().length > 6) {
      //   callback('长度限制不能超过6位数')
      // }
      // callback()
    },
  },
};
</script>

<style>
</style>
<style scoped>
.limitLength {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.inlineForm .el-form-item {
  width: 20%;
}
.oneLineForm .el-form-item {
  width: 100%;
}
.no-bottom-form .el-form-item {
  margin-bottom: 0px;
}
.column-two-form .el-form-item {
  width: calc(50% - 16px);
  display: inline-block;
}
.column-three-form .el-form-item {
  width: calc(33% - 10px);
  display: inline-block;
}
.el-form-item ::v-deep .el-form-item__content {
  max-width: calc(100% - 80px);
}
</style>
